<!--
    账号管理 P24
-->
<template>

    <PanelHead :title="panelTitle" :description="panelDescription"/>
    <div class="btns">
        <el-button icon="Plus" type="primary" @click="open(null)" >新增</el-button>
    </div>
    <el-table :data="tableData.list" border style="width: 100%">
        <el-table-column prop="id" label="id"  width="90" />
        <el-table-column prop="username" label="用户名"  />
        <el-table-column prop="name" label="姓名"  />
        <el-table-column prop="active" label="状态"  >
            <template #default="scope">
                <el-tag :type="scope.row.active==1 ? 'success':'danger'">{{ scope.row.active==1 ? '正常':'失效' }}</el-tag>
            </template>
        </el-table-column>
        <el-table-column label="创建时间"  >
            <template #default="scope">
                <div class="flex-box">
                    <el-icon><Clock /></el-icon>
                    <span style="margin-left: 10px"> {{ scope.row.createTime }} </span>
                </div>

            </template>
        </el-table-column>

        <el-table-column label="修改时间"  >
            <template #default="scope">
                <div v-if="scope.row.updateTime" class="flex-box">
                    <el-icon><Clock /></el-icon>
                    <span style="margin-left: 10px"> {{ scope.row.updateTime }} </span>
                </div>

            </template>
        </el-table-column>

        <el-table-column label="操作" width="180" >
            <template #default="scope">
                <el-button type="primary" @click="open(scope.row)">编辑</el-button>
            </template>
        </el-table-column>


    </el-table>
    <div class="pagination-info">
        <el-pagination
                v-model:current-page="paginationData.pageNum"
                :page-size="paginationData.pageSize"
                size="small"
                :background="false"
                layout="total, prev, pager, next"
                :total="tableData.total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
        >

        </el-pagination>
    </div>

    <el-dialog
            v-model="dialogFormVisible"
            :title="dialogTitle"
            width="500"
            :before-close="beforeClose"
    >
        <el-form
                ref="formRef"
                label-width="100px"
                label-position="left"
                :model="form"
                :rules="rules"
        >
            <el-form-item v-show="false" prop="id">
                <el-input v-model="form.id" />
            </el-form-item>
            <el-form-item label="用户名" prop="username">
               <el-input v-model="form.username" placeholder="请填写" :disabled="!isEditDialog"/>
            </el-form-item>
            <el-form-item label="名称" prop="name">
                <el-input v-model="form.name" placeholder="请填写" />
            </el-form-item>

            <el-form-item label="状态" >
                <!-- 下拉 -->
                <el-select
                        v-model="form.active"
                        placeholder="请选择"
                        size="large"
                        style="width: 240px"
                >
                    <el-option
                            v-for="item in options"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                    />
                </el-select>
            </el-form-item>


        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="confirm(formRef)" >确认</el-button>
            </div>
        </template>

    </el-dialog>
</template>
<script setup>
    import { userList, updateUser } from '../../../api/modules/userApi'
    import {nextTick, onMounted, reactive, ref} from "vue";
    import { userMenuList } from "../../../api";

    onMounted(()=>{
        // 发送请求，获得表格数据
        getTableData();

        // 菜单数据
        //console.log(data);
    });

    // 下拉值
    const value = ref('');
    // 下拉选项
    const options = [
        { value: 0, label: '失效' },
        { value: 1, label: '正常' },
    ];

    // 编辑表单
    const formRef = ref();

    // 表单数据定义
    const form = reactive(
        {
            id: '',
            username: '',
            name:'',
        });

    // 分页定义
    const paginationData = reactive({
        pageNum: 1,
        pageSize: 10
    });

    // 列表数据
    const tableData = reactive({
        list:  [
        ],
        total: 1
    });

    // 请求列表数据
    const getTableData = () => {
        userList(paginationData).then(({ data }) => {
            const { list, total } = data.data;
            tableData.list = list;
            tableData.total = total;
            console.log('请求返回',data.data);
            console.log('表格数据',tableData)
        } )
    };



    // 弹窗的显示隐藏
    const dialogFormVisible = ref(false);

    const isEditDialog =  ref(false);


    // 关闭弹窗的回调
    const beforeClose = () => {
        console.log("关闭弹窗--call");
        dialogFormVisible.value = false;
        // 重置表单
        formRef.value.resetFields();

    };

    // 打开弹窗
    const open = ( rowData = {} ) => {
        dialogFormVisible.value = true;

        // 弹窗打开form生成是异步的 如果新增和编辑是复用一个
        nextTick(() => {

                // 编辑页面赋值
                if(rowData){
                    //console.log(rowData);
                    Object.assign(form, {   id:rowData.id,
                                                    username: rowData.username,
                                                    name: rowData.name,
                                                    active: rowData.active
                    });
                    // treeRef.value.setCheckedKeys()
                    dialogTitle.value = "编辑用户";
                    isEditDialog.value = false;
                } else {
                    dialogTitle.value = "新增用户";
                    isEditDialog.value = true;
                    Object.assign(form, {   id: -1,
                        active:1
                    });
                }
            }
        )
    };

    // 页面数据变更
    const handleSizeChange = (val) => {
        console.log('数据变更');
        paginationData.pageNum = val;
        getTableData();
    };

    // 当前页码改变
    const handleCurrentChange = (val) => {
        console.log('页面变更');
        paginationData.pageNum = val;
        getTableData();
    };

    // 表单提交
    const confirm = async (formEl) => {

        if (!formEl) return;
        await formEl.validate((valid, fields) => {
            if (valid) {
                // 校验成功！
                const { id, name, username,active } = form;

                if ( id == -1){
                    ElMessage.success("新增用户待完善！");
                    // 关闭弹窗
                    beforeClose();
                }
                else{
                    // 发送请求
                    updateUser({ id, name, username,active }).then(({data}) => {
                        if (data.code === '0' ){
                            ElMessage.success(data.data);
                            getTableData();

                        }else {
                            ElMessage.error( data.msg);
                        }

                        // 关闭弹窗
                        beforeClose();
                    })
                }


            } else {
                console.log('error',fields);
            }
        });

    };

    // 用户名校验
    const validateName = (rule,value,callback) => {
        if(value === ''){
            callback(new Error('名称不能为空'));
        }
        callback();
    };

    // 状态校验
    const validateActive = (rule,value,callback) => {
        if(value === ''){
            callback(new Error('请选择状态'));
        }
        callback();
    };

    // 表单校验 blur失去焦点时触发
    const rules = reactive({
        name: [{ validator : validateName, trigger: 'blur'}],
        active: [{ validator : validateActive, trigger: 'blur'}],
    });

    const dialogTitle = ref('窗口标题');

    const panelTitle = ref('用户管理');
    const panelDescription = ref('管理员可以进行编辑，权限修改后需要登出才会生效');
</script>
<style lang="less" scoped>
    .btns{
        padding: 10px 0 10px 10px;
        background-color: #fff;
    }

    .flex-box {
        display: flex;
        /* 垂直剧中*/
        align-items: center;
        height: 100%;
    }
</style>